package org.jeecg.modules.system.util.dingding;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class DingdingUtils {

    private static OkHttpClient client = new OkHttpClient();
    /**
     * 发送钉钉消息
     * @param jsonString 消息内容
     * @param webhook 钉钉自定义机器人webhook
     * @return
     */
    public static boolean sendToDingding(String secret,String jsonString, String webhook) {
        try{
            Long timestamp = System.currentTimeMillis();
            StringBuilder url = new StringBuilder(webhook);
            url.append("&timestamp="+timestamp);
            if(StringUtils.isNotBlank(secret)){
                String stringToSign = timestamp + "\n" + secret;
                Mac mac = Mac.getInstance("HmacSHA256");
                mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
                byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
                String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
                url.append("&sign="+sign);
            }

            String type = "application/json; charset=utf-8";
            RequestBody body = RequestBody.create(MediaType.parse(type), jsonString);
            Request.Builder builder = new Request.Builder().url(url.toString());
            builder.addHeader("Content-Type", type).post(body);
            Request request = builder.build();
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            log.info(String.format("send ding message:%s", string));
            JSONObject res = JSONObject.parseObject(string);
            return res.getIntValue("errcode") == 0;

        }catch (Exception e){
            log.error("method:sendToDingding,发送钉钉群失败，失败原因",e.getMessage(),e);
            return false;
        }
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        TextEntity textEntity = new TextEntity();
        textEntity.setIsAtAll(false);
        textEntity.setContent("我就是我测试");
        List<String> atMobiles = Arrays.asList("189526916211");
        textEntity.setAtMobiles(atMobiles);
        String jsonStr =  textEntity.getJSONObjectString();
        String secret = "SECc5bfa92ab47bbd3fbe497cf94eb71034df0a1980f246f7cfc05089b85e944594";
        String webhook = "https://oapi.dingtalk.com/robot/send?access_token=6746c2fe52a5bccfcaba67f4bc3841c7cf36e1fb703a35b007bd06e9f09d7ad4";
        sendToDingding(secret,jsonStr,webhook);
    }

}
